package com.ucode.search.crm.service.impl;

import java.util.List;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ucode.search.crm.model.ESContacts;
import com.ucode.search.crm.service.ESContactsService;
import com.ucode.springboot.starter.ESsearch.repository.ElasticsearchSearchTemplate;
import com.ucode.springboot.starter.ESsearch.repository.query.Advanc;
import com.ucode.springboot.starter.ESsearch.repository.query.HighLight;
import com.ucode.springboot.starter.ESsearch.repository.query.PageSortHighLight;
import com.ucode.tool.base.Paginator;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;

@Service
public class ESContactsServiceImpl implements ESContactsService{

    @Autowired
    private ElasticsearchSearchTemplate<ESContacts, Long> esSearchTemplate;
    

    @Override
    public Paginator<ESContacts> searchByUser(List<Long> userIds, String keyword, Integer pageNum, Integer pageSize) throws Exception {
        PageSortHighLight pageSortHighLight = new PageSortHighLight(pageNum, pageSize);
        
        //非公海
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        
        if(StrUtil.isNotBlank(keyword)){
            //为了提高通配符模糊查询效率 建议输入关键字的长度
           QueryBuilder keywordQueryBuilder = QueryBuilders.boolQuery().should(QueryBuilders.matchPhrasePrefixQuery("name", keyword).maxExpansions(50))
                   .should(QueryBuilders.queryStringQuery("*"+keyword+"*").field("mobile"))
                   .should(QueryBuilders.queryStringQuery("*"+keyword+"*").field("telephone"));
           
           queryBuilder = queryBuilder.must(keywordQueryBuilder);
           
           HighLight highLight = pageSortHighLight.getHighLight();
           highLight.field("name");
           highLight.field("mobile");
           highLight.field("telephone");
        }
        
        
        if(CollUtil.isNotEmpty(userIds)){
            String userIdsStr = StrUtil.join(" ", userIds);
            queryBuilder = queryBuilder.must(QueryBuilders.multiMatchQuery(userIdsStr, "ownerUserIdStr","collaborator"));
        }
        
        
        Advanc advanc = new Advanc();
        advanc.setPageSortHighLight(pageSortHighLight);
        advanc.setIncludes(new String[]{"id","customerId","createUserId"});
//        advanc.setExcludes(new String[]{"ownerUserIdStr","teamUserIds"});
        //注意：如果includes为null的情况下excludes中包含用match的条件，设置了excludes也无效

        return esSearchTemplate.search(queryBuilder, advanc, ESContacts.class);
    }


    
}
